package staff.io;

import static staff.util.StringUtils.TXT_PARAM_DELIMITER;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import staff.logic.Employee;

/**
 * Class for save employes to text file. Parameters will be save according to
 * Employe.FieldsTags definition
 */
public class TxtEmployeSaver implements EmployeSaver {
    private Writer writer;

    public TxtEmployeSaver(String fileName) throws IOException {
        writer = new BufferedWriter(new FileWriter(fileName));
    }

    public void close() {
        try {
            writer.close();
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    public void saveNext(Employee employe) {
        String employeString = makeEmployeString(employe);
        try {
            writer.write(employeString);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    private String makeEmployeString(Employee employe) {
        StringBuilder employeString = new StringBuilder();
        // process all employe fields
        for (Employee.FieldTag tag : Employee.FieldTag.values()) {
            // save next employe param
            employeString.append(employe.getParamByName(tag.toString()));
            employeString.append(TXT_PARAM_DELIMITER);
        }
        employeString.append("\n");
        return employeString.toString();
    }

}
